from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework.settings import api_settings
from rest_framework_simplejwt.tokens import RefreshToken

from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import CustomTokenObtainPairSerializer

from user.models import SysUser

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .serializers import SysUserUpdateSerializer,SysUserSerializer

from rest_framework.permissions import AllowAny
from datetime import datetime

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from bilibili_management import settings
import json
from django.core.paginator import Paginator
from role.models import SysRole,SysUserRole

from django.contrib.auth.hashers import make_password

class LoginView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer


class UserUpdateView(APIView):
    permission_classes = [AllowAny]
    def post(self, request):
        data = request.data
        print("📥 收到数据:", data)

        user_id = data.get("id")  # ✅ 根据 id 查询

        # ✅ 新增用户逻辑开始
        if user_id == -1:
            if SysUser.objects.filter(username=data['username']).exists():
                return Response({"code": 400, "msg": "用户名已存在"})

            user = SysUser(
                username=data['username'],
                password=make_password("123456"),
                email=data.get("email", ""),
                phonenumber=data.get("phonenumber", ""),
                status=data.get("status", 1),
                remark=data.get("remark", ""),
                avatar="default.jpg",
                create_time=datetime.now().date()
            )
            user.save()
            return Response({"code": 200, "msg": "添加成功！"})
        # ✅ 新增用户逻辑结束

        # ✅ 这行是关键修正
        if user_id is None:
            return Response({"code": 400, "msg": "缺少用户 ID"})

        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return Response({"code": 404, "msg": "用户不存在"})

        serializer = SysUserUpdateSerializer(user, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"code": 200, "msg": "修改成功！"})
        return Response({"code": 400, "msg": "参数错误", "errors": serializer.errors})


@method_decorator(csrf_exempt, name="dispatch")
class UserChangePasswordView(APIView):
    permission_classes = [AllowAny]  # ✅ 跟原来一致，不需要登录 token

    def post(self, request):
        data = request.data
        print("📥 收到密码修改数据:", data)

        user_id = data.get("id")
        old_password = data.get("oldPassword")
        new_password = data.get("newPassword")

        if not user_id or not old_password or not new_password:
            return Response({"code": 400, "msg": "参数不完整"})

        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return Response({"code": 404, "msg": "用户不存在"})

        if user.password != old_password:
            return Response({"code": 403, "msg": "原密码错误！"})

        user.password = new_password
        user.update_time = datetime.now().date()
        user.save()

        return Response({"code": 200, "msg": "密码修改成功！"})
# Create your views here.
# class TestView(View):
#     def get(self,request):
#         userList_obj=SysUser.objects.all()  #从数据库中取出所有用户对象，返回的是一个 QuerySet 对象
#         # print(userList_obj,type(userList_obj))
#         userList_dict=userList_obj.values() # 转存字典，把 QuerySet 转换为字典格式
#         # print(userList_dict, type(userList_dict))
#         userList=list(userList_dict) # 把外层的容器转存List，转为真正的 Python 列表
#         print(userList, type(userList))
#         return JsonResponse({'code':200,'info':'测试！','data':userList}) #返回 JSON 响应

class ImageView(View):

    def post(self, request):
        file = request.FILES.get('avatar')
        print("file:", file)
        if file:
            file_name = file.name
            suffixName = file_name[file_name.rfind("."):]
            new_file_name = datetime.now().strftime('%Y%m%d%H%M%S') + suffixName
            file_path = str(settings.MEDIA_ROOT) + "\\userAvatar\\" + new_file_name
            print("file_path:", file_path)
            try:
                with open(file_path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
                return JsonResponse({'code': 200, 'title': new_file_name})
            except:
                return JsonResponse({'code': 500, 'errorInfo': '上传头像失败'})

class AvatarView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        id = data['id']
        avatar = data['avatar']
        obj_user = SysUser.objects.get(id=id)
        obj_user.avatar = avatar
        obj_user.save()
        return JsonResponse({'code': 200})

class SearchView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数
        print(pageSize, pageNum)
        userListPage = Paginator(SysUser.objects.filter(username__icontains=query).order_by('id'), pageSize).page(pageNum)
        print(userListPage)
        obj_users = userListPage.object_list.values()  # 转成字典
        users = list(obj_users)  # 把外层的容器转成List
        for user in users:
            userId = user['id']
            roleList = SysRole.objects.raw(
                "SELECT id,NAME FROM sys_role WHERE id IN (SELECT role_id FROM sys_user_role WHERE user_id=" + str(
                    userId) + ")")
            roleListDict = []
            for role in roleList:
                roleDict = {}
                roleDict["id"] = role.id
                roleDict["name"] = role.name
                roleListDict.append(roleDict)
            user['roleList'] = roleListDict
        total = SysUser.objects.filter(username__icontains=query).count()
        return JsonResponse({'code': 200, 'userList': users, 'total': total})

class ActionView(View):

    def get(self, request):
        """
        根据id获取用户信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        user_object = SysUser.objects.get(id=id)
        return JsonResponse({'code': 200, 'user': SysUserSerializer(user_object).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        SysUserRole.objects.filter(user_id__in=idList).delete()
        SysUser.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})

class CheckView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        username = data['username']
        print("username=", username)
        if SysUser.objects.filter(username=username).exists():
            return JsonResponse({'code': 500})
        else:
            return JsonResponse({'code': 200})

class PasswordView(View):

    def get(self, request):
        id = request.GET.get("id")
        user_object = SysUser.objects.get(id=id)
        user_object.password = "123456"
        user_object.update_time = datetime.now().date()
        user_object.save()
        return JsonResponse({'code': 200})

class StatusView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        id = data['id']
        status = data['status']
        user_object = SysUser.objects.get(id=id)
        user_object.status = status
        user_object.save()
        return JsonResponse({'code': 200})

class GrantRole(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        user_id = data['id']
        roleIdList = data['roleIds']
        print(user_id, roleIdList)
        SysUserRole.objects.filter(user_id=user_id).delete()  # 删除用户角色关联表中的指定用户数据
        for roleId in roleIdList:
            userRole = SysUserRole(user_id=user_id, role_id=roleId)
            userRole.save()
        return JsonResponse({'code': 200})

class TestView(View):

    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if token != None and token != '':
            userList_obj = SysUser.objects.all()
            print(userList_obj, type(userList_obj))
            userList_dict = userList_obj.values()  # 转存字典
            print(userList_dict, type(userList_dict))
            userList = list(userList_dict)  # 把外层的容器转存List
            print(userList, type(userList))
            return JsonResponse({'code': 200, 'info': '测试！', 'data': userList})
        else:
            return JsonResponse({'code': 401, 'info': '没有访问权限！'})

class JwtTestView(View):
    def get(self, request):
        try:
            user = SysUser.objects.get(username='python222', password='123456')
        except SysUser.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '用户不存在'})

        # 用 simplejwt 生成 token
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)
        refresh_token = str(refresh)

        return JsonResponse({
            'code': 200,
            'access_token': access_token,
            'refresh_token': refresh_token,
        })

# class LoginView(View):
#
#     def post(self, request):
#         username = request.GET.get("username")
#         password = request.GET.get("password")
#         try:
#             user = SysUser.objects.get(username=username, password=password)
#             jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#             jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#             # 将用户对象传递进去，获取到该对象的属性值
#             payload = jwt_payload_handler(user)
#             # 将属性值编码成jwt格式的字符串
#             token = jwt_encode_handler(payload)
#         except Exception as e:
#             print(e)
#             return JsonResponse({'code': 500, 'info': '用户名或者密码错误！'})
#         return JsonResponse({'code': 200, 'token': token, 'info': '登录成功'})